package ch.sfug.controls {
	import flash.display.InteractiveObject;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;

	import ch.sfug.events.ButtonGroupEvent;	

	/**
	 * this class manages an array of buttons where only one can be active.
	 * the active button will automatically mouseEnabled = false and mouseEnabled = true when another one wil become active.
	 * 
	 */
	 
	/**
	 * Dispatched when the user clicks on one button of the group
	 *
	 * @eventType ch.sfug.events.ButtonGroupEvent.ACTIVATE
	 */
	[Event(name="buttongroup_deactivate", type="ch.sfug.events.ButtonGroupEvent")]

	/**
	 * Dispatched when the user clicks on one button of the group and the old one will be deactivated.
	 *
	 * @eventType ch.sfug.events.ButtonGroupEvent.DEACTIVATE
	 */
	[Event(name="buttongroup_deactivate", type="ch.sfug.events.ButtonGroupEvent")]

	public class ButtonGroup extends EventDispatcher {

		private var _selected:InteractiveObject;
		private var buttonArray:Array;

		public function ButtonGroup() {
			super();
			buttonArray = new Array();
		}

		/**
		 * adds an interactiveObject to the button group.
		 */
		public function addButton( btn:InteractiveObject ):void {
			buttonArray.push(btn);
			btn.addEventListener(MouseEvent.CLICK, doClick);
		}

		
		/**
		 * removes a button from the group
		 */
		public function removeButton( btn:InteractiveObject ):void {
			for(var i:Number = 0;i < buttonArray.length; i++) {
				if(buttonArray[i] == btn) {
					btn.removeEventListener(MouseEvent.CLICK, doClick);
					buttonArray.splice(i, 1);
				}
			}
		}

		
		/**
		 * this shortcut function automatically activates the passed button
		 */
		public function activate( io:InteractiveObject ):void {
			io.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		}

		
		
		/**
		 * clears the group with all buttons
		 */
		public function removeAll():void {
			for(var i:Number = 0;i < buttonArray.length; i++) {
				buttonArray[i].removeEventListener(MouseEvent.CLICK, doClick);
			}
			buttonArray = new Array();
		}

		/**
		 * returns an array with all buttons in the group
		 */
		public function get buttons():Array {
			return buttonArray.slice();
		}

		/**
		 * returns the active button. if no button is active it will return null
		 */
		public function get active():InteractiveObject {
			return _selected;
		}

		
		private function doClick( evt:MouseEvent ):void {	
			if(evt.currentTarget != _selected) {
				
				deactivate();
				
				_selected = InteractiveObject(evt.currentTarget);
				_selected.mouseEnabled = false;
				dispatchEvent(new ButtonGroupEvent(ButtonGroupEvent.ACTIVATE, _selected));
			}
		}
		
		
		public function deactivate():void {
			if(_selected != null) {
					dispatchEvent(new ButtonGroupEvent(ButtonGroupEvent.DEACTIVATE, _selected));
					_selected.mouseEnabled = true;
					_selected = null;
				}
		}
	}
}